package com.ywdnf.gomoku.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * json工具类
 *
 * @author lss
 * @date 2019-02-03, Sun
 */
public class JsonUtil {

    /**
     * 日志打印
     */
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    /**
     * json mapper
     */
    private static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

    }

    /**
     * 转换对象为JSON String
     *
     * @param object json对象
     * @return 字符串
     */
    public static String toJsonString(Object object) {
        if (object == null) {
            return null;
        }
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("", e);
        }
        return "";
    }

    /**
     * 转换字符串为对象
     *
     * @param json  json字符串
     * @param clazz 对象class
     * @return obj
     */
    public static <T> T readValue(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            logger.error("", e);
            return null;
        }
    }

    /**
     * 将字符串转换成Map
     *
     * @param json 要转换的字符串
     * @return Map
     */
    public static Map<String, Object> convertToMap(String json) {
        Map<String, Object> map;
        try {
            map = JsonUtil.mapper.readValue(json, new TypeReference<Map<String, Object>>() {
            });
        } catch (IOException e) {
            logger.error("parse json error");
            return null;
        }
        return map;
    }
}
